package com.zckj.jcServer;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MiddlewareMqttClient {

    private  String host;
    private  String port;
    private  String account;
    private  String password;
    private  String clientId;
    private  String topic;

    public MiddlewareMqttClient(String host, String port, String account, String password, String clientId, String topic) {
        this.host = host;
        this.port = port;
        this.account = account;
        this.password = password;
        this.clientId = clientId;
        this.topic = topic;
    }

    private static MqttClient client;
    //生成配置对象，用户名，密码等
    public MqttConnectOptions getOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(account);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(100000);
        options.setKeepAliveInterval(30);
//        options.setMqttVersion(4);
        options.setWill("root_server",(clientId+"客户端close").getBytes(),0,true);
        return options;
    }
    public void connect() throws MqttException {
        //防止重复创建MQTTClient实例
        if (client==null) {
            client = new MqttClient(host + ":" + port, clientId, new MemoryPersistence());
            client.setCallback(new PushCallback(MiddlewareMqttClient.this));
        }
        MqttConnectOptions options = getOptions();
        //判断拦截状态，这里注意一下，如果没有这个判断，是非常坑的
        if (!client.isConnected()) {
            client.connect(options);
        }else {//这里的逻辑是如果连接成功就重新连接
            client.disconnect();
            client.connect(getOptions());
        }
    }
    //监听设备发来的消息
    public void subscribeMessage() throws MqttException {
        //getMessage是我自己封装的一个订阅主题的函数，对于聪明的你们，应该很简单吧
        getMessage(topic, 2);
    }

    public void connect(int number) {
        for (int i = 0; i < number||number>999; i++) {
            try {
                connect();
            } catch (Exception e) {
                e.printStackTrace();
                //Thread.sleep(5000);
                System.err.println("连接失败,正在第"+i+"次尝试");
                continue;
            }
            return;
        }
        throw new RuntimeException("无法连接服务器");
    }

    //init连接
    public void init() throws MqttException {
        connect(100);
    }

    public  void  getMessage(String topic, int qos) throws MqttException {
            client.subscribe(topic,qos);
    }

    public  void  publishMessage(String topic, String msg) throws MqttException {
        MqttMessage message = new MqttMessage();
        message.setQos(2);
        message.setPayload(msg.getBytes());
        message.setRetained(true);
        client.publish(topic,message);
    }

    public  void  closeClient() throws MqttException {
        client.close();
    }

    public  void  disconnctClient() throws MqttException {
        client.disconnect();
    }
}
